package cn.com.woxitech.dev.controller;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.qiniu.storage.UploadManager;



import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import cn.com.woxitech.dev.common.APIResult;
import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.CodeUtils;
import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.EncryptionUtils;
import cn.com.woxitech.dev.common.HttpClientUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.QiniuPhotoUploadUtils;
import cn.com.woxitech.dev.common.StrUtils;
import cn.com.woxitech.dev.model.Lecture;
import cn.com.woxitech.dev.model.QiniuUploadResult;
import cn.com.woxitech.dev.model.RoomManager;
import cn.com.woxitech.dev.model.WmChathistoryFetch;
import cn.com.woxitech.dev.model.gen.WeixinApiAccessToken;
import cn.com.woxitech.dev.model.gen.WmApp;
import cn.com.woxitech.dev.model.gen.WmCatalog;
import cn.com.woxitech.dev.model.gen.WmLecture;
import cn.com.woxitech.dev.model.gen.WmLecturePage;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.PrivilegeService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.SettingService;
import cn.com.woxitech.dev.service.UserService;
import cn.com.woxitech.dev.service.WeixinService;

@RestController
@RequestMapping("/wjt")
public class AdminWJTController {
	@Autowired
	WeixinService weixinService;
	@Autowired
	SettingService settingService;
	@Autowired
	PrivilegeService privilegeService;
	@Autowired
	QiniuService qiniuService;
	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	@Autowired
	UserService userService;
	@Autowired
	SMSCodeService smsCodeService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	CatalogService catalogService;	
	@Autowired
	AppService appService;
	
	
		


	@RequestMapping(value="/wjt_admin_catalog_init",method=RequestMethod.POST)
	public Object wjt_admin_catalog_init(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);

			WmApp  app = this.appService.getDefaultWmApp();
			List<WmCatalog> list = this.catalogService.getCatalogs(app.getId());
			
			
			mp.put("app", app);
			mp.put("catalogs", list);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}

	@RequestMapping(value="/wjt_chairinvite_init",method=RequestMethod.POST)
	public Object wjt_chairinvite_init(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String roomuuid =jsonNode.get("roomuuid").asText();
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			
			List<Map<String, Object>> user_chairs = this.roomService.getRoomChairs(roomuuid); 
			
			mp.put("roomname", room.getName());
			mp.put("roomuuid", room.getUuid());
			mp.put("chairs",user_chairs);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}

	@RequestMapping(value="/wjt_user_init",method=RequestMethod.POST)
	public Object wjt_user_init(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			
			WmUser user = this.userService.getUserByUuid(useruuid);

			mp.put("user", user);
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/wjt_room_details_init",method=RequestMethod.POST)
	public Object wjt_room_details_init(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String roomuuid =jsonNode.get("roomuuid").asText();
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			if(!roomService.hasManagePrivilegeForRoom(room,useruuid)){
				return APIResultFactory.fail("您没有该微讲堂管理权限");
			}
			
			WmLecture lecture = this.lectureService.getLectureByRoomUuid(roomuuid);
			List<WmLecturePage> lecturePages = this.lecturePageService.getLecturePageByLectureUuid(lecture.getUuid());
			String cataloguuid = "";
			WmCatalog catalog = this.catalogService.getUndefaultCatalogByRoomUuid(room.getUuid());
			if(catalog != null){
				cataloguuid = catalog.getUuid();
			}

			WmApp wmApp = this.appService.getDefaultWmApp();
			List<WmCatalog> catalogs = this.catalogService.getCatalogs(wmApp.getId());
			mp.put("catalogs", catalogs);
			mp.put("room", room);
			mp.put("ratio", lecture.getRatio());
			mp.put("lps", lecturePages);
			mp.put("cataloguuid", cataloguuid);
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	

	@RequestMapping(value="/wjt_create_init",method=RequestMethod.POST)
	public Object wjt_create_init(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			
			
			WmApp wmApp = this.appService.getDefaultWmApp();
			List<WmCatalog> catalogs = this.catalogService.getCatalogs(wmApp.getId());
			
			mp.put("catalogs", catalogs);
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/wjt_admin_member_init",method=RequestMethod.POST)
	public Object wjt_admin_member_init(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String s = jsonNode.get("s").asText();
			String p = jsonNode.get("p").asText();
			String w = jsonNode.get("w").asText();
			
			int _s = 10;
			int _p = 1;
			
			if(!s.equals("")){
				_s=StrUtils.strToInt(s, _s);
				_p=StrUtils.strToInt(p, _p);
			}
			
			int total = this.userService.countAllUsersBySearchKeywords(w,_p,_s);
			int current = _p;
			List<WmUser> users = this.userService.getAllUsersBySearchKeywords(w,_p,_s);
			
			mp.put("total", total);
			mp.put("current", current);
			mp.put("users", users);
			
			mp = addFooterCopyright(mp);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/wjt_admin_init",method=RequestMethod.POST)
	public Object wjt_admin_init(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String s = jsonNode.get("s").asText();
			String p = jsonNode.get("p").asText();
			String w = jsonNode.get("w").asText();
			String c = (jsonNode.get("c").asText()).trim();
			
			int _s = 10;
			int _p = 1;
			
			if(!s.equals("")){
				_s=StrUtils.strToInt(s, _s);
				_p=StrUtils.strToInt(p, _p);
			}
			
			int current = _p;
			
			
					
			Map<String,Object> room_mp = this.roomService.getRoomsOfSomeBodyBySearchTitle(w,_p,_s,useruuid, c);
			int total = (Integer) room_mp.get("total"); 
			List<WmRoom> rooms = (ArrayList<WmRoom>)room_mp.get("rooms");		 
			WmApp wmApp = this.appService.getDefaultWmApp();
			List<WmCatalog> catalogs = this.catalogService.getCatalogs(wmApp.getId());
			
			mp.put("catalogs", catalogs);
			mp.put("total", total);
			mp.put("current", current);
			mp.put("rooms", rooms);
			
			mp = addFooterCopyright(mp);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	
	
	@RequestMapping(value="/admin_setting",method=RequestMethod.POST)
	public Object admin_setting_init(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			
			
			List<WeixinApiAccessToken> waatlist = this.weixinService.getWeixinApiAccessTokenList();
			for(WeixinApiAccessToken waat : waatlist){
				if(waat.getName().equals(Const.WX_FUWUORQIYE)){
					mp.put("wx_id", waat.getAppid());
					mp.put("wx_secret", waat.getSecretid());
				}else if(waat.getName().equals(Const.WX_KAIFANG)){
					mp.put("wx_open_id", waat.getAppid());
					mp.put("wx_open_secret", waat.getSecretid());					
				}
				
			}

			mp = addAttachmentPath(mp);
			mp = addFooterCopyright(mp);
			mp = addHostname(mp);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	

	private Map<String, Object> addHostname(Map<String, Object> mp) {
		// TODO Auto-generated method stub
		String val = this.settingService.getSettingVal(Const.WEB_HOSTNAME);
		if(val == null){
//			val="http://localhost:8080";
			val="";
		}
		mp.put("admin_web_hostname", val);
		return mp;
	}


	private Map<String, Object> addAttachmentPath(Map<String, Object> mp) {
		// TODO Auto-generated method stub
		String val = this.settingService.getSettingVal(Const.ATTACHMENT_PATH);
		if(val == null){
			val="";
		}
		mp.put("admin_attachment_path", val);
		return mp;
	}



	private Map<String, Object> addFooterCopyright(Map<String, Object> mp) {
		// TODO Auto-generated method stub
		String copyright = this.settingService.getSettingVal(Const.ADMIN_COPYRIGHT);
		if(copyright == null){
			copyright = Const.ADMIN_COPYRIGHT_DEFAULT;
		}
		mp.put("admin_copyright", copyright);
		return mp;
	}

	
	
	
	@RequestMapping(value="/wjt_room_basic_update",method=RequestMethod.POST)
	public Object wjt_room_basic_update(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String roomuuid =jsonNode.get("roomuuid").asText();
			String name = jsonNode.get("name").asText();
			String starttime = jsonNode.get("starttime").asText();
			String endtime = jsonNode.get("endtime").asText();
			starttime = starttime.replace("T", " ");
			endtime = endtime.replace("T", " ");
			String des= jsonNode.get("des").asText();
			String cataloguuid = jsonNode.get("cataloguuid").asText();
			String roomchairs = jsonNode.get("roomchairs").asText();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");                
			Date _starttime = sdf.parse(starttime);
			Date _endtime = sdf.parse(endtime);
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			room.setName(name);
			room.setTime(_starttime);
			room.setEndtime(_endtime);
			room.setDes(des);
			room.setRoomchairs(roomchairs);
			
			if(this.roomService.hasManagePrivilegeForRoom(room, useruuid)){
				roomService.updateByPrimaryKey(room);	
				
				if(cataloguuid.equals("")){
					WmCatalog c = this.catalogService.getUndefaultCatalogByRoomUuid(room.getUuid());
					if(c != null){
						catalogService.deleteByCatalogUUidAndRoomUuid(c.getUuid(), room.getUuid());	
					}
					
				}else{
					WmCatalog c = this.catalogService.getUndefaultCatalogByRoomUuid(room.getUuid());
					if(c != null){
						catalogService.deleteByCatalogUUidAndRoomUuid(c.getUuid(), room.getUuid());	
					}
					catalogService.insertCatalog_Room(cataloguuid, room.getUuid());
				}
				
			}else{
				return APIResultFactory.fail("您没有该微讲堂管理权限");
			}
			
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail(Const.ERROR_EXCEPTION);
		}
		
	}
	

	
	
	@RequestMapping(value="/admin_sysinfo_save",method=RequestMethod.POST)
	public Object admin_sysinfo_save(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String wjt_admin_copyright = jsonNode.get("wjt_admin_copyright").asText();
			String wjt_admin_attachment_path = jsonNode.get("wjt_admin_attachment_path").asText();
			String wjt_admin_web_hostname = jsonNode.get("wjt_admin_web_hostname").asText();
			
			if(wjt_admin_copyright == null || wjt_admin_copyright.equals("")){
				settingService.saveSettingVal(Const.ADMIN_COPYRIGHT, Const.ADMIN_COPYRIGHT_DEFAULT);
			}else{
				settingService.saveSettingVal(Const.ADMIN_COPYRIGHT, wjt_admin_copyright);
			}
			
			settingService.saveSettingVal(Const.ATTACHMENT_PATH, wjt_admin_attachment_path);
			settingService.saveSettingVal(Const.WEB_HOSTNAME, wjt_admin_web_hostname);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/wjt_roomcreate",method=RequestMethod.POST)
	public Object wjt_roomcreate(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			
			String orguuid = this.organizationService.getDefaultOrganization().getUuid();
			
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String name = jsonNode.get("name").asText();
			String starttime = jsonNode.get("starttime").asText();
			starttime = starttime.replace("T", " ");
			String createpwd= jsonNode.get("createpwd").asText();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");                
			Date _starttime = sdf.parse(starttime);
			Date _endtime = new Date(_starttime.getTime() + 1000*3600);
			Date createtime = new Date(System.currentTimeMillis());
			
			String cataloguuid= jsonNode.get("cataloguuid").asText();
			
			WmUser user = this.userService.getUserByUuid(useruuid);
			
			//创建room
			WmRoom room = new WmRoom();
			room.setRoomchairs(user.getName());
			room.setName(name);
			room.setDes("");
			room.setCreatoruuid(useruuid);
			room.setOrguuid(orguuid);
			room.setCreatetime(createtime);
			room.setTime(_starttime);
			room.setEndtime(_endtime);
			room.setType("1");
			room.setThumburl(Const.WJT_THUMB_DEFAULT);
			room.setUuid(UUID.randomUUID().toString());
			if(createpwd.equals("1")){
				room.setPwd(CodeUtils.generateVerifyCode(4));
			}
			roomService.insertRoom(room);
			
			//创建Lecture
			WmLecture lecture = new WmLecture();
			lecture.setName(name);
			lecture.setRatio("0.5625");
			lecture.setTime(createtime);
			lecture.setRoomid(room.getUuid());
			lecture.setUuid(UUID.randomUUID().toString());
			lecture.setCreatorid(room.getCreatoruuid());
			lectureService.insertLecture(lecture);
			
			mp.put("roomuuid", room.getUuid());
			
			WmCatalog catalog_all = this.catalogService.getCatalogByName(Const.CATALOG_ALL);
			this.catalogService.insertCatalog_Room(catalog_all.getUuid(), room.getUuid());
			if(!cataloguuid.equals("")){
				this.catalogService.insertCatalog_Room(cataloguuid, room.getUuid());	
			}
			
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail(Const.ERROR_EXCEPTION);
		}
		
	}
	

	@RequestMapping(value="/wx_setting_save",method=RequestMethod.POST)
	public Object wx_setting_save(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			
			if(!privilegeService.hasAdminRole(useruuid)){
				return APIResultFactory.fail("你没有对应权限");
			}
			
			String wx_id = jsonNode.get("wx_id").asText();
			String wx_secret = jsonNode.get("wx_secret").asText();
			String wx_open_id = jsonNode.get("wx_open_id").asText();
			String wx_open_secret = jsonNode.get("wx_open_secret").asText();
			
			weixinService.saveWeixinAppIdAndSecret(wx_id,wx_secret,Const.WX_FUWUORQIYE);
			weixinService.saveWeixinAppIdAndSecret(wx_open_id,wx_open_secret,Const.WX_KAIFANG);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail(Const.ERROR_EXCEPTION);
		}
		
	}
	

	@RequestMapping(value="/wjt_lecture_ratio_update",method=RequestMethod.POST)
	public Object wjt_lecture_ratio_update(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String roomuuid = jsonNode.get("roomuuid").asText();
			String ratio = jsonNode.get("ratio").asText();

			WmLecture l = this.lectureService.getLectureByRoomUuid(roomuuid);
			l.setRatio(ratio);
			this.lectureService.updateByPrimaryKey(l);

			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/userinfo_admin_pwd_update",method=RequestMethod.POST)
	public Object userinfo_admin_pwd_update(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String wjt_user_pwd_new = jsonNode.get("wjt_user_pwd_new").asText();
			
			
			WmUser user = this.userService.getUserByUuid(useruuid);
			
			user.setPwd(EncryptionUtils.pwd(wjt_user_pwd_new));
			this.userService.updateUser(user);

			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/wjt_delete_room",method=RequestMethod.POST)
	public Object wjt_delete_room(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String roomuuid =jsonNode.get("roomuuid").asText();
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			WmLecture lecture = this.lectureService.getLectureByRoomUuid(room.getUuid());
			try{
				this.lecturePageService.deleteByLectureUuid(lecture.getUuid());
			}catch(Exception e){}
			try{
				this.lectureService.deleteByRoomUuid(room.getUuid());
			}catch(Exception e){}
			try{
				this.roomService.deleteByPrimarykey(room);
			}catch(Exception e){}
			
//			this.catalogService.deleteByRoomUuid(room.getUuid());
				
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/userinfo_pwd_update",method=RequestMethod.POST)
	public Object userinfo_pwd_update(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String wjt_user_pwd_old = jsonNode.get("wjt_user_pwd_old").asText();
			String wjt_user_pwd_new = jsonNode.get("wjt_user_pwd_new").asText();
			String wjt_user_pwd_new2 = jsonNode.get("wjt_user_pwd_new2").asText();
			
			if(!wjt_user_pwd_new.equals(wjt_user_pwd_new2)){
				return APIResultFactory.fail("两次新密码不一致");
			}
			
			WmUser user = this.userService.getUserByUuid(useruuid);
			
			String oldpwd = user.getPwd();
			
			
			if(EncryptionUtils.pwdvs(wjt_user_pwd_old, oldpwd)){
				user.setPwd(EncryptionUtils.pwd(wjt_user_pwd_new));
				this.userService.updateUser(user);
			}else{
				return APIResultFactory.fail("原密码输入不正确");
			}

			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	@RequestMapping(value="/admin_pwd_update",method=RequestMethod.POST)
	public Object admin_pwd_update(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String wjt_adminpwd_old = jsonNode.get("wjt_adminpwd_old").asText();
			String wjt_adminpwd_new = jsonNode.get("wjt_adminpwd_new").asText();
			String wjt_adminpwd_new2 = jsonNode.get("wjt_adminpwd_new2").asText();
			
			if(!wjt_adminpwd_new.equals(wjt_adminpwd_new2)){
				return APIResultFactory.fail("两次新密码不一致");
			}
			
			
			String oldpwd = settingService.getSettingVal(Const.ADMIN_PWD);
			if(oldpwd == null){
				settingService.saveSettingVal(Const.ADMIN_PWD, wjt_adminpwd_new);
			}else{
				if(oldpwd.equals(wjt_adminpwd_old)){
					settingService.saveSettingVal(Const.ADMIN_PWD, wjt_adminpwd_new);
				}else{
					return APIResultFactory.fail("原密码输入不正确");
				}
			}

			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	

	@RequestMapping(value="/room_pwd_switch",method=RequestMethod.POST)
	public Object room_pwd_switch(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String roomuuid = jsonNode.get("roomuuid").asText();
			String pwd = jsonNode.get("pwd").asText();
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			
			if(pwd.equals("1")){
				room.setPwd(CodeUtils.generateSMSVerifyCode(4));
			}else{
				room.setPwd("");
			}
			
			this.roomService.updateByPrimaryKey(room);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}

	@RequestMapping(value="/room_staging",method=RequestMethod.POST)
	public Object room_staging(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid =jsonNode.get("useruuid").asText();
			String roomuuid = jsonNode.get("roomuuid").asText();
			String staging = jsonNode.get("staging").asText();
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			
			if(staging.equals("1")){
				room.setDoortemplate(Const.STAGING_TEMPLATE_DEFAULT);
			}else{
				room.setDoortemplate("");
			}
			
			this.roomService.updateByPrimaryKey(room);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value = "/upload_wjt_staging/{roomuuid}", method = RequestMethod.POST)
	public Object upload_wjt_staging(@RequestParam("file") MultipartFile file, @PathVariable String roomuuid) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			
			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/img/";
//			filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key;
			
			File f_path = new File(filebase);
			if(!f_path.exists()){
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if(!f_key.exists()){
				f_key.createNewFile();
			}
			
			FileOutputStream fos =new FileOutputStream(f_key);
					
			fos.write(bytes);
			
			fos.flush();
			fos.close();
			
			String web_path =  StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.WEB_HOSTNAME)) +"/attachment/img/"+ key;
			String relative_path = "/attachment/img/"+ key;
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			room.setCoverurl(relative_path);
			this.roomService.updateByPrimaryKey(room);
			
			mp.put("key", key);
			mp.put("path",web_path);
			
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}


	@RequestMapping(value="/upload_lecture_ppt_pic/{roomuuid}",method=RequestMethod.POST)
	public Object upload_lecture_ppt_pic(@RequestParam("file") MultipartFile file, @PathVariable String roomuuid) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			
			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/img/";
//			filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key;
			
			File f_path = new File(filebase);
			if(!f_path.exists()){
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if(!f_key.exists()){
				f_key.createNewFile();
			}
			
			FileOutputStream fos =new FileOutputStream(f_key);
					
			fos.write(bytes);
			
			fos.flush();
			fos.close();
			
			String picture_url=UploadQiniuPic(bytes);
			String web_path =  StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.WEB_HOSTNAME)) +"/attachment/img/"+ key;
			String relative_path = picture_url;
			
			WmLecture lecture = this.lectureService.getLectureByRoomUuid(roomuuid);
			WmLecturePage lp = new WmLecturePage();
			lp.setLectureid(lecture.getUuid());
			lp.setNum(20);
			lp.setType("img");
			lp.setPageurl(relative_path);
			lp.setTime(new Date(System.currentTimeMillis()));
			this.lecturePageService.insertLecturePage(lp);
			
			mp.put("key", key);
			mp.put("path",web_path);
			
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}
	//图片上传七牛并返回绝对地址
	private String UploadQiniuPic(byte[]bytes){
		try {
			String filename = "localimg_" + UUID.randomUUID().toString()+".jpg";
			// 密钥配置
			Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
			String bucket = Const.Bucket_HAOJSQINIU;
			// 创建上传对象
			UploadManager uploadManager = new UploadManager();
			
			String uploadToken = auth.uploadToken(bucket);
			
			uploadManager.put(bytes, filename, uploadToken);
			String pic_url=Const.QINIU_BASE_URL+'/'+filename;
			return pic_url;

		} catch (Exception e) {
			e.printStackTrace();
			return "null";
		}
	}
	
	
	@RequestMapping(value="/upload_lecture_video_thumb/{id}",method=RequestMethod.POST)
	public Object upload_lecture_video_thumb(@RequestParam("file") MultipartFile file, @PathVariable String id) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			
			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/img/";
//			filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key;
			
			File f_path = new File(filebase);
			if(!f_path.exists()){
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if(!f_key.exists()){
				f_key.createNewFile();
			}
			
			FileOutputStream fos =new FileOutputStream(f_key);
					
			fos.write(bytes);
			
			fos.flush();
			fos.close();
			
			String web_path =  StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.WEB_HOSTNAME)) +"/attachment/img/"+ key;
			String relative_path = "/attachment/img/"+ key;
			
			WmLecturePage lp = this.lecturePageService.selectByPrimaryKey(Integer.parseInt(id));
			lp.setThumburl(relative_path);
			this.lecturePageService.updateByPrimaryKey(lp);
			
			mp.put("key", key);
			mp.put("path",web_path);
			
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}
	
	

	@RequestMapping(value = "/upload_user_thumb_create", method = RequestMethod.POST)
	public Object upload_user_thumb_create(@RequestParam("file") MultipartFile file) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			
			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/img/";
//			filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key;
			
			File f_path = new File(filebase);
			if(!f_path.exists()){
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if(!f_key.exists()){
				f_key.createNewFile();
			}
			
			FileOutputStream fos =new FileOutputStream(f_key);
					
			fos.write(bytes);
			
			fos.flush();
			fos.close();
			
			String web_path =  StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.WEB_HOSTNAME)) +"/attachment/img/"+ key;
			String relative_path = "/attachment/img/"+ key;
			
			mp.put("key", key);
			mp.put("path",web_path);
			mp.put("relative_path",relative_path);
			
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}
	
	
	@RequestMapping(value = "/upload_user_thumb/{useruuid}", method = RequestMethod.POST)
	public Object upload_user_thumb(@RequestParam("file") MultipartFile file, @PathVariable String useruuid) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			
			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/img/";
//			filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key;
			
			File f_path = new File(filebase);
			if(!f_path.exists()){
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if(!f_key.exists()){
				f_key.createNewFile();
			}
			
			FileOutputStream fos =new FileOutputStream(f_key);
					
			fos.write(bytes);
			
			fos.flush();
			fos.close();
			
			String web_path =  StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.WEB_HOSTNAME)) +"/attachment/img/"+ key;
			String relative_path = "/attachment/img/"+ key;
			
			WmUser user = this.userService.getUserByUuid(useruuid);
			user.setWxHeadimgurl(relative_path);
			this.userService.updateUser(user);
			
			mp.put("key", key);
			mp.put("path",web_path);
			
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}
	
	
	
	@RequestMapping(value = "/upload_wjt_cover/{roomuuid}", method = RequestMethod.POST)
	public Object upload_wjt_cover(@RequestParam("file") MultipartFile file, @PathVariable String roomuuid) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			
			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/img/";
//			filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key;
			
			File f_path = new File(filebase);
			if(!f_path.exists()){
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if(!f_key.exists()){
				f_key.createNewFile();
			}
			
			FileOutputStream fos =new FileOutputStream(f_key);
					
			fos.write(bytes);
			
			fos.flush();
			fos.close();
			
			String web_path =  StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.WEB_HOSTNAME)) +"/attachment/img/"+ key;
			String relative_path = "/attachment/img/"+ key;
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			room.setLivecoverurl(relative_path);
			this.roomService.updateByPrimaryKey(room);
			
			mp.put("key", key);
			mp.put("path",web_path);
			
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}
	
	@RequestMapping(value = "/upload_wjt_logo/{roomuuid}", method = RequestMethod.POST)
	public Object upload_wjt_logo(@RequestParam("file") MultipartFile file, @PathVariable String roomuuid) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			
			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/img/";
//			filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key;
			
			File f_path = new File(filebase);
			if(!f_path.exists()){
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if(!f_key.exists()){
				f_key.createNewFile();
			}
			
			FileOutputStream fos =new FileOutputStream(f_key);
					
			fos.write(bytes);
			
			fos.flush();
			fos.close();
			
			String web_path =  StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.WEB_HOSTNAME)) +"/attachment/img/"+ key;
			String relative_path = "/attachment/img/"+ key;
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			room.setThumburl(relative_path);
			this.roomService.updateByPrimaryKey(room);
			
			mp.put("key", key);
			mp.put("path",web_path);
			
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}
	
	
	@RequestMapping(value="/room_lecturepage_video_save",method=RequestMethod.POST)
	public Object room_lecturepage_video_save(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			int id = jsonNode.get("id").asInt();
			String pageurl = jsonNode.get("pageurl").asText();
			String roomuuid = jsonNode.get("roomuuid").asText();
			if(id != 0){//如果已经存在，这里先根据id号是否已经存在进行判断，如果已经存在，那么保存后就是修改，这里可以利用this.lecturePageService.selectByPrimaryKey()定位数据库id号，从而get到数据库元组中的url。
				WmLecturePage lp = this.lecturePageService.selectByPrimaryKey(id);
				System.out.println(lp.getPageurl());//打印URL
				lp.setPageurl(pageurl);//修改URL
				this.lecturePageService.updateByPrimaryKey(lp);
			}else{
				String lectureid = this.lectureService.getLectureByRoomUuid(roomuuid).getUuid();
				WmLecturePage lp = new WmLecturePage();
				lp.setLectureid(lectureid);
				lp.setNum(20);
				lp.setType("video");
				lp.setPageurl(pageurl);
				lp.setTime(new Date(System.currentTimeMillis()));
				this.lecturePageService.insertLecturePage(lp);
			}
			
			mp.put("id", ""+id);
			mp.put("pageurl", pageurl);
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	//--------------以下为转码-------------
	@RequestMapping(value="/room_video_transcoding",method=RequestMethod.POST)
	public void room_video_transcoding(@RequestBody String body) {
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String pageurl = jsonNode.get("pageurl").asText();
			String roomuuid = jsonNode.get("roomuuid").asText();
			String SrcFileName=pageurl.substring(30);
			System.out.println(SrcFileName);
			System.out.println(roomuuid);
			String NewName="ZhuanMa_"+roomuuid+".mp4";
			String NewPageUrl="http://obxfmzcpx.bkt.clouddn.com/"+NewName;
//视频转码
			
			//设置账号的AK,SK
//		  String ACCESS_KEY = "Access_Key";
//		  String SECRET_KEY = "Secret_Key";
			Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
			//新建一个OperationManager对象
			OperationManager operater = new OperationManager(auth);
			//设置要转码的空间和key，并且这个key在你空间中存在
			String bucket = "haojslive";
			String key = SrcFileName;
			//设置转码操作参数
			String fops = "avthumb/mp4";
			//设置转码的队列
			String pipeline = Const.PIPELINE_NAME;
			//可以对转码后的文件进行使用saveas参数自定义命名，当然也可以不指定文件会默认命名并保存在当前空间。
			String urlbase64 = UrlSafeBase64.encodeToString("haojslive"+":"+NewName);
			String pfops = fops + "|saveas/"+urlbase64;
			//设置pipeline参数
			StringMap params = new StringMap().putWhen("force", 1, true).putNotEmpty("pipeline", pipeline);
			try {
				String persistid = operater.pfop(bucket, key, pfops, params);
				//打印返回的persistid
				System.out.println(persistid);
				//String NewMp4="http://obxfmzcpx.bkt.clouddn.com/"+"zhuanma_2";
				System.out.println(NewPageUrl);
				System.out.println("-----done-----");
			} catch (QiniuException e) {
				//捕获异常信息
				Response r = e.response;
				// 请求失败时简单状态信息
				System.out.println(r.toString());
				try {
					// 响应的文本信息
					System.out.println(r.bodyString());
				} catch (QiniuException e1) {
					//ignore
				}
			}
//		  // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
//					String token = getUpToken(auth, bucket, pfops, pipeline);
//				    System.out.println("getUpToken已上传");
//				    String NewMp4="http://obxfmzcpx.bkt.clouddn.com/"+"zhuanma_2";
//				    System.out.println(NewMp4);
//				    System.out.println("----done----");
//					// String token = auth.uploadToken(HJSConstants.Bucket_WMHISTORY);
//					// 调用put方法上传
//			//		Response res = uploadManager.put(bytes, filename + ".amr", token);
			
			
//以上视频转码
			
			//上传阿里云并反馈给前端
			String lectureid = this.lectureService.getLectureByRoomUuid(roomuuid).getUuid();
			WmLecturePage lp = new WmLecturePage();
			lp.setLectureid(lectureid);
			lp.setNum(15);//上传本地视频设为12，转码视频设为15
			lp.setType("video");
			lp.setPageurl(NewPageUrl);
			lp.setTime(new Date(System.currentTimeMillis()));
			this.lecturePageService.insertLecturePage(lp);
			
			
			}catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		
		
		
		
		
/*		JsonNode jsonNode;
//		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			int id = jsonNode.get("id").asInt();
//			String pageurl = jsonNode.get("pageurl").asText();
//			String roomuuid = jsonNode.get("roomuuid").asText();
//			  if(id != 0){//如果已经存在，这里先根据房间号是否已经存在进行判断，如果已经存在，那么保存后就是修改，这里可以利用this.lecturePageService.selectByPrimaryKey()定位房间号，从而get到房间中的url。
				WmLecturePage lp = this.lecturePageService.selectByPrimaryKey(id);
				System.out.println("————————下载————————");
				System.out.println(lp.getPageurl());//打印URL
				String DownloadUrl=lp.getPageurl();
				String TempFilePath="file:///Users/dongmingchao/Downloads/";//+"123456.mp4";
				File dirFile = new File(TempFilePath);
				 if(!dirFile.exists()){//文件路径不存在时，自动创建目录
			          dirFile.mkdirs();
			        }
				//调用下载函数
				// System.out.println("调用下载函数");
				//getDownload(DownloadUrl,TempFilePath+"1234.mp4");//传入下载地址，本地地保存路径。
//				lp.setPageurl(pageurl);//修改URL
//				this.lecturePageService.updateByPrimaryKey(lp);
//			  }else{
//				String lectureid = this.lectureService.getLectureByRoomUuid(roomuuid).getUuid();
//				WmLecturePage lp = new WmLecturePage();
//				lp.setLectureid(lectureid);
//				lp.setNum(20);
//				lp.setType("video");
//				lp.setPageurl(pageurl);
//				lp.setTime(new Date(System.currentTimeMillis()));
//				this.lecturePageService.insertLecturePage(lp);
//			  }
			
//			mp.put("id", ""+id);
//			mp.put("pageurl", pageurl);
//			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("下载失败");
			//return APIResultFactory.fail();
		}
*/		
	}
	
//getUpToken
//	public static String getUpToken(Auth auth, String bucketname, String pfops, String pipeline) {
//		return auth.uploadToken(bucketname, null, 3600,
//				new StringMap().putNotEmpty("persistentOps", pfops).putNotEmpty("persistentPipeline", pipeline), true);
//	}
	
	
	//后台下载（暂时未用）
	 private static void getDownload(String url,String pathName)throws Exception{
	        URL ul = new URL(url);
	        HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
	        BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
	        FileOutputStream bs = new FileOutputStream(pathName);
	        System.out.println("文件大约："+(conn.getContentLength()/1024)+"K");
	        byte[] by = new byte[1024];
	        int len = 0;
	        while((len=bi.read(by))!=-1){
	            bs.write(by,0,len);
	        }
	        bs.close();
	        bi.close();
	    }
	
	//以上
	
	@RequestMapping(value="/lecture_page_order_update",method=RequestMethod.POST)
	public Object lecture_page_order_update(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			int id = jsonNode.get("id").asInt();
			int num = jsonNode.get("num").asInt();
			
			WmLecturePage lp = this.lecturePageService.selectByPrimaryKey(id);
			lp.setNum(num);
			this.lecturePageService.updateByPrimaryKey(lp);
			
			mp.put("id", ""+id);
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	@RequestMapping(value="/lecture_page_delete",method=RequestMethod.POST)
	public Object deleteLecturePage(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			int id = jsonNode.get("id").asInt();
			lecturePageService.deleteByPrimaryKey(id);
			
			mp.put("id", ""+id);
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}

	 
	

	@RequestMapping(value="/userinfo_create",method=RequestMethod.POST)
	public Object userinfo_create(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			
			String name = jsonNode.get("name").asText();
			String email = jsonNode.get("email").asText();
			String phone = jsonNode.get("phone").asText();
			String pwd = jsonNode.get("pwd").asText();
			String thumb = jsonNode.get("thumb").asText();
			
			WmUser user = new WmUser();
			user.setWxHeadimgurl(thumb);
			user.setPwd(pwd);
			user.setName(name);
			user.setTel(phone);
			user.setEmail(email);
			user.setUuid(UUID.randomUUID().toString());
			user.setCreatetime(new Date(System.currentTimeMillis()));
			
			this.userService.insertUser(user);
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/wjt_removechair",method=RequestMethod.POST)
	public Object wjt_removechair(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
			String useruuid = jsonNode.get("useruuid").asText();
			
			this.roomService.removeRoomChair(roomuuid,useruuid);
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	@RequestMapping(value="/wjt_addchair",method=RequestMethod.POST)
	public Object wjt_addchair(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
			String email = jsonNode.get("email").asText();
			
			WmUser user = this.userService.getUserByEmail(email);
			if(user == null){
				return APIResultFactory.fail("未找到邮件为【"+email+"】的用户");
			}
			
			int chair_count = this.roomService.countRoomChairs(roomuuid, user.getUuid());
			if(chair_count >0){
				return APIResultFactory.fail("已经添加过邮件为【"+email+"】的用户");
			}
			
			this.roomService.addRoomChair(roomuuid, user.getUuid());
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	@RequestMapping(value="/userinfo_udpate",method=RequestMethod.POST)
	public Object userinfo_udpate(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid = jsonNode.get("useruuid").asText();
			String name = jsonNode.get("name").asText();
			String email = jsonNode.get("email").asText();
			String phone = jsonNode.get("phone").asText();
			
			WmUser user = this.userService.getUserByUuid(useruuid);
			user.setName(name);
			user.setTel(phone);
			user.setEmail(email);
			
			this.userService.updateUser(user);
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	

	@RequestMapping(value="/dologin",method=RequestMethod.POST)
	public Object dologin(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String email = jsonNode.get("email").asText();
			String pwd = jsonNode.get("pwd").asText();
			
			if(email.equals("sa")){
				
				String pwd_en = this.settingService.getSettingVal(Const.ADMIN_PWD);
				if(pwd_en == null || pwd_en.equals("")){
					mp.put("useruuid", "sa");
					mp.put("username", "sa");
					mp.put("isAdmin", "1");
				}else {
					if(EncryptionUtils.pwdvs(pwd, pwd_en)){
						mp.put("useruuid", "sa");
						mp.put("username", "sa");
						mp.put("isAdmin", "1");
					}else{
						return APIResultFactory.fail("用户密码不正确，请重试");
					}
					
				}

				
			}else{
				
				WmUser user = this.userService.getUserByEmail(email);
				
				if(user == null){
					user = this.userService.getUserByTel(email);
					if(user == null){
						return APIResultFactory.fail("用户密码不正确，请重试");	
					}
					
				}
				
				if(!EncryptionUtils.pwdvs(pwd, user.getPwd())){
					return APIResultFactory.fail("用户密码不正确，请重试");
				}
				
				user.setLastlogin(new Date(System.currentTimeMillis()));
				this.userService.updateUser(user);
				
				mp.put("useruuid", user.getUuid());
				mp.put("username", user.getName());
				mp.put("isAdmin", "0");
				mp.put("headimgurl", user.getWxHeadimgurl());
				
			}
	
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	

	@RequestMapping(value="/catalog_order_save",method=RequestMethod.POST)
	public Object catalog_order_save(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			
			String name = jsonNode.get("name").asText();
			
			WmApp app = this.appService.getDefaultWmApp();
			WmCatalog c = this.catalogService.getCatalogByName(name);
			List<WmCatalog> list = this.catalogService.getCatalogs(app.getId());
			if(c == null){
				WmCatalog catalog = list.get(0);
				catalog.setName(name);
				catalog.setUuid(UUID.randomUUID().toString());
				catalog.setOrdernum(list.size()+1);
				this.catalogService.insertCatalog(catalog);
			}else{
				return APIResultFactory.fail("已有当前分类");
			}
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	

	@RequestMapping(value="/catalog_del",method=RequestMethod.POST)
	public Object catalog_del(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			
			String uuid = jsonNode.get("uuid").asText();
			
			this.catalogService.deleteByCatalogUuid(uuid);
			this.catalogService.deleteCatalogRoomByCatalogUuid(uuid);
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	@RequestMapping(value="/catalog_change",method=RequestMethod.POST)
	public Object catalog_change(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			
			String uuid = jsonNode.get("uuid").asText();
			String name = jsonNode.get("name").asText();
			
			WmCatalog catalog = this.catalogService.getCatalogByUuid(uuid);
			catalog.setName(name);
			this.catalogService.updateWmCatalog(catalog);
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	@RequestMapping(value="/catalog_order_update",method=RequestMethod.POST)
	public Object catalog_order_update(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			
			String uuid = jsonNode.get("uuid").asText();
			String ordernum = jsonNode.get("ordernum").asText();
			
			WmCatalog catalog = this.catalogService.getCatalogByUuid(uuid);
			catalog.setOrdernum(Integer.parseInt(ordernum));
			this.catalogService.updateWmCatalog(catalog);
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
}
